package com.ace.lab.starter.meta;

import lombok.Getter;
import lombok.Setter;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Setter
@Getter
public class DiscoveredMetadata {
    private String name;
    private boolean async;
    private List<ServiceAddress> addressList = new ArrayList<>();

    public void addAddress(String ip_port) {
        ServiceAddress address = new ServiceAddress();
        String[] split = ip_port.split(":");
        address.setIp(split[0]);
        address.setPort(Integer.parseInt(split[1]));
        addressList.add(address);
    }

    public void removeAddress(String ip_port) {
        addressList.removeIf(address -> address.getIdentity().equals(ip_port));
    }

    @Setter
    @Getter
    public class ServiceAddress {
        private String ip;
        private int port;

        String getIdentity() {
            return ip + ":" + port;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            ServiceAddress that = (ServiceAddress) o;
            return port == that.port &&
                    Objects.equals(ip, that.ip);
        }

        @Override
        public int hashCode() {
            return Objects.hash(ip, port);
        }
    }
}
